/**
 * 数据存储管理类
 * 负责项目配置、环境状态的持久化存储
 */
class DataStorage {
  constructor(storage) {
    this.storage = storage;
    this.configKey = 'switcher3-config';
    this.defaultConfig = {
      projects: {
        // 预置示例项目
        'driving-wizard': {
          id: 'driving-wizard',
          name: '驱动精灵',
          environments: {
            test: 'dgvip360.drivergenius3.com 127.0.0.1:8181\napi.drivergenius.com 127.0.0.1:8182',      // 测试环境配置
            production: 'dgvip360.drivergenius3.com 101.201.28.186:80\napi.drivergenius.com 101.201.28.187:80' // 生产环境配置
          },
          customRules: [], // 自定义规则列表
          activeEnvironment: 'test' // 当前激活的环境：'test', 'production', 'custom:ruleId', null
        },
        'duba': {
          id: 'duba',
          name: '毒霸',
          environments: {
            test: 'api.duba.net 192.168.1.100:8080\ncdn.duba.com 192.168.1.101:3000',
            production: 'api.duba.net 47.93.187.142:80\ncdn.duba.com 47.93.187.143:80'
          },
          customRules: [],
          activeEnvironment: null
        }
      },
      projectOrder: ['driving-wizard', 'duba'], // 项目显示顺序
      lastProjectId: null // 最后操作的项目ID
    };
    
    this.ensureConfig();
  }

  /**
   * 确保配置文件存在，不存在则创建默认配置
   */
  ensureConfig() {
    try {
      const config = this.loadConfig();
      if (!config || !config.projects) {
        console.log('[Switcher3] 初始化默认配置');
        this.saveConfig(this.defaultConfig);
      }
    } catch (error) {
      console.error('[Switcher3] 配置初始化失败:', error);
      this.saveConfig(this.defaultConfig);
    }
  }

  /**
   * 加载配置数据
   */
  loadConfig() {
    try {
      const configData = this.storage.getProperty(this.configKey);
      if (!configData) {
        return this.defaultConfig;
      }
      
      const config = JSON.parse(configData);
      
      // 合并默认配置，确保数据结构完整
      return {
        ...this.defaultConfig,
        ...config,
        projects: {
          ...this.defaultConfig.projects,
          ...config.projects
        }
      };
    } catch (error) {
      console.error('[Switcher3] 加载配置失败:', error);
      return this.defaultConfig;
    }
  }

  /**
   * 保存配置数据
   */
  saveConfig(config) {
    try {
      const configToSave = {
        ...config,
        lastUpdated: new Date().toISOString()
      };
      
      this.storage.setProperty(this.configKey, JSON.stringify(configToSave));
      console.log('[Switcher3] 配置保存成功');
      return true;
    } catch (error) {
      console.error('[Switcher3] 保存配置失败:', error);
      return false;
    }
  }

  /**
   * 获取所有项目
   */
  getAllProjects() {
    const config = this.loadConfig();
    return config.projects || {};
  }

  /**
   * 获取项目列表（按顺序）
   */
  getProjectList() {
    const config = this.loadConfig();
    const projects = config.projects || {};
    const projectOrder = config.projectOrder || [];
    
    return projectOrder.map(id => projects[id]).filter(Boolean);
  }

  /**
   * 获取单个项目
   */
  getProject(projectId) {
    const config = this.loadConfig();
    return config.projects[projectId] || null;
  }

  /**
   * 创建新项目
   */
  createProject(name) {
    const config = this.loadConfig();
    const projectId = this.generateProjectId(name);
    
    const newProject = {
      id: projectId,
      name: name,
      environments: {
        test: '',
        production: ''
      },
      customRules: [],
      activeEnvironment: null,
      createdAt: new Date().toISOString()
    };
    
    config.projects[projectId] = newProject;
    config.projectOrder.push(projectId);
    config.lastProjectId = projectId;
    
    this.saveConfig(config);
    return newProject;
  }

  /**
   * 更新项目
   */
  updateProject(projectId, updates) {
    const config = this.loadConfig();
    
    if (!config.projects[projectId]) {
      throw new Error(`项目不存在: ${projectId}`);
    }
    
    config.projects[projectId] = {
      ...config.projects[projectId],
      ...updates,
      updatedAt: new Date().toISOString()
    };
    
    // 如果更新了项目名称，重新生成ID
    if (updates.name && updates.name !== config.projects[projectId].name) {
      const newId = this.generateProjectId(updates.name);
      if (newId !== projectId) {
        // 创建新项目条目
        config.projects[newId] = {
          ...config.projects[projectId],
          id: newId,
          name: updates.name
        };
        
        // 更新顺序数组
        const orderIndex = config.projectOrder.indexOf(projectId);
        if (orderIndex !== -1) {
          config.projectOrder[orderIndex] = newId;
        }
        
        // 删除旧项目条目
        delete config.projects[projectId];
        
        projectId = newId;
      }
    }
    
    this.saveConfig(config);
    return config.projects[projectId];
  }

  /**
   * 删除项目
   */
  deleteProject(projectId) {
    const config = this.loadConfig();
    
    if (!config.projects[projectId]) {
      throw new Error(`项目不存在: ${projectId}`);
    }
    
    delete config.projects[projectId];
    
    // 从顺序数组中移除
    const orderIndex = config.projectOrder.indexOf(projectId);
    if (orderIndex !== -1) {
      config.projectOrder.splice(orderIndex, 1);
    }
    
    // 如果删除的是最后操作的项目，清空记录
    if (config.lastProjectId === projectId) {
      config.lastProjectId = null;
    }
    
    this.saveConfig(config);
    return true;
  }

  /**
   * 更新项目环境配置
   */
  updateEnvironment(projectId, environment, config) {
    const projectConfig = this.loadConfig();
    
    if (!projectConfig.projects[projectId]) {
      throw new Error(`项目不存在: ${projectId}`);
    }
    
    if (!['test', 'production'].includes(environment)) {
      throw new Error(`无效的环境类型: ${environment}`);
    }
    
    projectConfig.projects[projectId].environments[environment] = config;
    projectConfig.projects[projectId].updatedAt = new Date().toISOString();
    
    this.saveConfig(projectConfig);
    return projectConfig.projects[projectId];
  }

  /**
   * 添加自定义规则
   */
  addCustomRule(projectId, label, value) {
    const config = this.loadConfig();
    
    if (!config.projects[projectId]) {
      throw new Error(`项目不存在: ${projectId}`);
    }
    
    const ruleId = this.generateRuleId();
    const newRule = {
      id: ruleId,
      label: label,
      value: value,
      createdAt: new Date().toISOString()
    };
    
    config.projects[projectId].customRules.push(newRule);
    config.projects[projectId].updatedAt = new Date().toISOString();
    
    this.saveConfig(config);
    return newRule;
  }

  /**
   * 更新自定义规则
   */
  updateCustomRule(projectId, ruleId, updates) {
    const config = this.loadConfig();
    
    if (!config.projects[projectId]) {
      throw new Error(`项目不存在: ${projectId}`);
    }
    
    const ruleIndex = config.projects[projectId].customRules.findIndex(rule => rule.id === ruleId);
    if (ruleIndex === -1) {
      throw new Error(`规则不存在: ${ruleId}`);
    }
    
    config.projects[projectId].customRules[ruleIndex] = {
      ...config.projects[projectId].customRules[ruleIndex],
      ...updates,
      updatedAt: new Date().toISOString()
    };
    
    config.projects[projectId].updatedAt = new Date().toISOString();
    
    this.saveConfig(config);
    return config.projects[projectId].customRules[ruleIndex];
  }

  /**
   * 删除自定义规则
   */
  deleteCustomRule(projectId, ruleId) {
    const config = this.loadConfig();
    
    if (!config.projects[projectId]) {
      throw new Error(`项目不存在: ${projectId}`);
    }
    
    const ruleIndex = config.projects[projectId].customRules.findIndex(rule => rule.id === ruleId);
    if (ruleIndex === -1) {
      throw new Error(`规则不存在: ${ruleId}`);
    }
    
    config.projects[projectId].customRules.splice(ruleIndex, 1);
    config.projects[projectId].updatedAt = new Date().toISOString();
    
    // 如果删除的规则正在被激活，清除激活状态
    if (config.projects[projectId].activeEnvironment === `custom:${ruleId}`) {
      config.projects[projectId].activeEnvironment = null;
    }
    
    this.saveConfig(config);
    return true;
  }

  /**
   * 设置项目激活环境
   */
  setActiveEnvironment(projectId, environment) {
    const config = this.loadConfig();
    
    if (!config.projects[projectId]) {
      throw new Error(`项目不存在: ${projectId}`);
    }
    
    // 验证环境类型
    if (environment !== null && 
        !['test', 'production'].includes(environment) && 
        !environment.startsWith('custom:')) {
      throw new Error(`无效的环境类型: ${environment}`);
    }
    
    config.projects[projectId].activeEnvironment = environment;
    config.projects[projectId].updatedAt = new Date().toISOString();
    config.lastProjectId = projectId;
    
    this.saveConfig(config);
    return config.projects[projectId];
  }

  /**
   * 获取所有激活的环境
   */
  getActiveEnvironments() {
    const config = this.loadConfig();
    const activeEnvironments = [];
    
    Object.values(config.projects).forEach(project => {
      if (project.activeEnvironment) {
        activeEnvironments.push({
          projectId: project.id,
          projectName: project.name,
          environment: project.activeEnvironment,
          activatedAt: project.activatedAt || new Date().toISOString()
        });
      }
    });
    
    return activeEnvironments;
  }

  /**
   * 激活环境
   */
  activateEnvironment(projectId, environment) {
    const config = this.loadConfig();
    
    if (!config.projects[projectId]) {
      throw new Error(`项目不存在: ${projectId}`);
    }
    
    console.log(`[Switcher3] DataStorage 激活环境: ${projectId} - ${environment}`);
    
    // 更新项目的激活环境
    config.projects[projectId].activeEnvironment = environment;
    config.projects[projectId].activatedAt = new Date().toISOString();
    config.lastUpdated = new Date().toISOString();
    
    this.saveConfig(config);
    console.log(`[Switcher3] 环境激活状态已保存: ${projectId} - ${environment}`);
  }

  /**
   * 停用环境
   */
  deactivateEnvironment(projectId) {
    const config = this.loadConfig();
    
    if (!config.projects[projectId]) {
      console.log(`[Switcher3] 项目不存在，跳过停用: ${projectId}`);
      return;
    }
    
    console.log(`[Switcher3] DataStorage 停用环境: ${projectId}`);
    
    // 清除项目的激活环境
    config.projects[projectId].activeEnvironment = null;
    config.projects[projectId].activatedAt = null;
    config.lastUpdated = new Date().toISOString();
    
    this.saveConfig(config);
    console.log(`[Switcher3] 环境停用状态已保存: ${projectId}`);
  }

  /**
   * 生成项目ID
   */
  generateProjectId(name) {
    const baseId = name.toLowerCase()
      .replace(/[^\w\s-]/g, '') // 移除特殊字符
      .replace(/\s+/g, '-')     // 空格替换为连字符
      .replace(/--+/g, '-')     // 多个连字符合并为一个
      .trim();
    
    // 如果生成的ID为空，使用时间戳
    if (!baseId) {
      return `project-${Date.now()}`;
    }
    
    // 检查ID是否已存在
    const config = this.loadConfig();
    if (!config.projects[baseId]) {
      return baseId;
    }
    
    // 如果存在，添加数字后缀
    let counter = 1;
    let newId = `${baseId}-${counter}`;
    while (config.projects[newId]) {
      counter++;
      newId = `${baseId}-${counter}`;
    }
    
    return newId;
  }

  /**
   * 生成规则ID
   */
  generateRuleId() {
    return `rule-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 重置配置（开发和调试用）
   */
  resetConfig() {
    console.log('[Switcher3] 重置配置到默认状态');
    this.saveConfig(this.defaultConfig);
    return this.defaultConfig;
  }

  /**
   * 获取配置统计信息
   */
  getStats() {
    const config = this.loadConfig();
    const projects = Object.values(config.projects);
    
    return {
      totalProjects: projects.length,
      activeProjects: projects.filter(p => p.activeEnvironment).length,
      totalCustomRules: projects.reduce((sum, p) => sum + p.customRules.length, 0),
      lastUpdated: config.lastUpdated
    };
  }
}

module.exports = DataStorage;